const path = require('path')
const fs = require('fs').promises

const uuid = require('uuid')


module.exports = () => {
    return async (ctx, next) => {
        if (ctx.path === '/form' && ctx.method.toLowerCase() === 'post') {

            let arr = []
            ctx.req.on('data', function (chunk) {
                arr.push(chunk)
            })
            ctx.req.on('end',  async ()=> {

                let fields = {}
                let allData = Buffer.concat(arr)
                //拿到每个字段之间的分隔符
                let boundary = '--' + ctx.get('Content-Type').split('=')[1]
                // console.log(Buffer.concat(arr).toString())
                //截取掉前后的内容
                let lines = allData.split(boundary).slice(1, -1)
                await Promise.all(lines.map(async line => {
                    let [head, body] = line.split('\r\n\r\n')
                    _head = head.toString() //二进制的head
                    let key = _head.match(/name="(.+)"/)[1]



                    if (!_head.includes('filename')) { //非文件


                        body = body.toString().slice(0, -2);
                        fields[key] = body
                    } else { //文件
                        let filePath = path.resolve(__dirname, 'upload', uuid.v4())
                        fields['filename'] = filePath
                        let content = line.slice(head.length + 4, -2)
                        await fs.writeFile(filePath, content)
                    }
                }))
                ctx.request.fields = fields
             

            })
            ctx.body =  ctx.request.fields
        }

    

    }
}